<template>
  <v-layout type="main">
    <div class="detail-layout">
      <el-steps :active="active" v-if="active != 9" finish-status="success" class="myself-steps" simple>
        <el-step title="基本信息"></el-step>
        <el-step title="上传文件"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
        <el-form class="form myself-form alick-add-form" ref="form" :model="addForm" :rules="submitRules" label-width="120px">        
        <div v-if="active == 1 || active == 9 ">
          <el-form-item label="名称" prop="name"><el-input type="text" v-model="addForm.name"  />
          </el-form-item>
          <h3 class="add-alike-title">仿真环境配置</h3>
          <el-form-item label="仿真环境">
            <el-select  v-model="simulation.image" value-key="id" @change="changeSimulationImage(simulation.image)"
              prop="simulation_image_id" class="full-extent-select">
              <el-option v-for="item in simulationImageOptions" :value="item" :label="item.name" :key="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="想定">
            <el-select  v-model="scenario" @change="changeScenario(scenario)" prop="scenario_id"
              class="full-extent-select">
              <el-option v-for="item in scenarioOptions" :value="item" :label="item.name" :key="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="推演方">
            <div class="outin-box" v-for="(e, i) in simulation_deduction_list" :key="i">
              <div class="outin-input">
                <div class="outin-input-name">                  
                  <el-form-item :label="e.name">
                      <el-select  v-model="e.type">
                          <el-option :value='1' label="人类" />
                          <el-option :value='2' label="模型" />
                      </el-select>
                  </el-form-item>
                  <el-form-item label="模型" prop="model_id">
                    <el-select v-model="e.model_id" value-key="id" @change="changeModel(e.model_id, i)" style="width:100%;"
                      :popper-append-to-body="false" popper-class="select-popper" placeholder="请选择">
                      <el-option v-for="item in modelOptions" :key="item.id" :label="item.name" :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="版本" prop="model_version_id">
                    <el-select v-model="e.model_version_id" value-key="id" @change=changeModelVersion() style="width:100%;"
                      :popper-append-to-body="false" popper-class="select-popper" placeholder="请选择">
                      <el-option v-for="item in e.modelVersionOptions" :key="item.id" :label="item.version"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="数量">
            <el-input-number v-model="simulation.pod_num"></el-input-number>
          </el-form-item>
          <el-form-item label="启动命令行" prop="command">
            <el-input type="textarea" @input="onInput"  :rows="2" v-model="simulation.command" />
          </el-form-item>
          <el-form-item label="端口" prop="port">
            <div class="outin-box" v-for="(e, i) in simulation_port_list" :key="i">
              <div class="port-lis">
                <el-radio-group v-model="e.protocol" class="port-lis-radio">
                  <el-radio :label="2">tcp</el-radio>
                  <el-radio :label="1">http</el-radio>
                </el-radio-group>
                <el-input type="text" v-model="e.port" class="port-el-input" />
              </div>
            </div>
          </el-form-item>
          <div class="node-module">
            <h3 class="node-module-title">主节点</h3>
            <el-form-item label="环境" prop="name">
              <div>
                <el-radio-group v-model="mainNode.visibility"
                  @change="changeMasterEngine(mainNode.visibility, mainNode.engine)" size="small">
                  <el-radio-button label='2'>公开的</el-radio-button>
                  <el-radio-button label='1'>共享的</el-radio-button>
                  <el-radio-button label='0'>我的</el-radio-button>
                </el-radio-group>
              </div>
              <el-radio-group v-model="mainNode.engine"
                @change="changeMasterEngine(mainNode.visibility, mainNode.engine)" size="small">
                <el-radio-button label='0'>Oneflow</el-radio-button>
                <el-radio-button label='2'>Pytorch</el-radio-button>
                <el-radio-button label='1'>TensorFlow</el-radio-button>
                <el-radio-button label='3'>其他</el-radio-button>
              </el-radio-group>
              <div class="select">
                <el-select  v-model="mainNode.image_id" class="full-extent-select">
                  <el-option v-for="item in mainNode.imageOptions" :value="item.id" :label="item.name" :key="item.id">
                  </el-option>
                </el-select>
              </div>
            </el-form-item>
            <el-form-item label="资源组">
              <el-select v-model="mainNode.product_id" class="full-extent-select">
                <el-option v-for="item in productOptions" :value="item.id" :label="item.name" :key="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="启动命令行" prop="command">
              <el-input type="textarea" :rows="2" v-model="mainNode.command" />
            </el-form-item>
            <div class="right-btn-box" v-if="slaveNodeList.length == 0">
              <span class="outin-handle">
                <a href="javascript:;" @click="addSlaveNode()">增加</a>
              </span>
            </div>
          </div>
          <div v-for="(tag, i) in slaveNodeList" :key="i">
            <div class="node-module">
              <h3 class="node-module-title">从节点</h3>

              <el-form-item label="环境" prop="name">
                <div>
                  <el-radio-group v-model="tag.visibility" @change="changeSlaveEngine(tag.visibility,tag.engine,i)"
                    size="small">
                    <el-radio-button label='2'>公开的</el-radio-button>
                    <el-radio-button label='1'>共享的</el-radio-button>
                    <el-radio-button label='0'>我的</el-radio-button>
                  </el-radio-group>
                </div>
                <el-radio-group v-model="tag.engine" size="small"
                  @change="changeSlaveEngine(tag.visibility,tag.engine,i)">
                  <el-radio-button label='0'>Oneflow</el-radio-button>
                  <el-radio-button label='2'>Pytorch</el-radio-button>
                  <el-radio-button label='1'>TensorFlow</el-radio-button>
                  <el-radio-button label='3'>其他</el-radio-button>
                </el-radio-group>
                <div class="select">
                  <el-select v-model="tag.image_id" class="full-extent-select">
                    <el-option v-for="item in tag.imageOptions" :value="item.id" :label="item.name" :key="item.id">
                    </el-option>
                  </el-select>
                </div>
              </el-form-item>
              <el-form-item label="资源组">
                <el-select  v-model="tag.product_id" class="full-extent-select">
                  <el-option v-for="item in productOptions" :value="item.id" :label="item.name" :key="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="数量">
                <el-input-number  v-model="tag.pod_num"></el-input-number>
              </el-form-item>
              <el-form-item label="启动命令行" prop="tag.command">
                <el-input type="textarea" :rows="2" v-model="tag.command" />
              </el-form-item>
              <!-- <a href="javascript:;" @click="delSlaveNode(i)">删除</a> -->
              <div class="right-btn-box">
                <span class="outin-handle">
                  <a href="javascript:;" @click="delSlaveNode(i)">删除</a>
                  <a href="javascript:;" @click="addSlaveNode()" v-if="i == slaveNodeList.length - 1">增加</a>
                </span>
              </div>
            </div>

          </div>
          <!-- <a href="javascript:;" @click="addSlaveNode()">增加</a> -->
          <el-form-item label="超参" prop="param">
            <div class="outin-box" v-for="(e, i) in parameter_list" :key="i">
              <div class="port-lis">
                <span class="outin-input-name-title">名称</span>
                <el-input type="text" v-model="e.name"  class="port-el-input" />
                <!-- <span class="outin-input-name-title">=</span> -->
                <span class="outin-input-name-title">值</span>
                <el-input type="text" v-model="e.value" class="port-el-input" />
              </div>
              <span class="outin-handle">
                <a href="javascript:;" @click="addParam(i)" v-if="i == parameter_list.length - 1">增加</a>
                <span v-else class="slot-btn"></span>
                <a href="javascript:;" @click="delParam(i)" v-if="parameter_list.length > 1">删除</a>
              </span>
            </div>
          </el-form-item>
        </div>
        <div v-if="active == 2 ">
          <p class="uploader-hint">文件会上传到/workspace目录下，会持久保存，重启容器时不会丢失</p>
          <el-form-item label="上传文件 " prop=" ">
            <wrapUploader @succeedOver="succeedOver" type="model" :taskId="path" :biz_id="bizId" />
          </el-form-item>
        </div>
        <div v-show="active == 3">
          <p class="succeed-hint">创建成功</p>
          <div class="succeed-btn">
            <a href="javascript:;" class="start" @click="startTask">启动</a>
            <a href="javascript:;" class="go" @click="toDetail">立即前往</a>
          </div>
        </div>
        <el-form-item label=" ">
          <el-button class="none-type" v-if="active == 1" @click="addTaskVersion">下一步</el-button>
          <el-button class="none-type" v-if="active == 2" @click="submmit">下一步</el-button>
          <el-button class="none-type" v-if="active == 9" @click="updateSubmmit">确定</el-button>
        </el-form-item>
      </el-form>
    </div>
  </v-layout>
</template>

<script>
import { addGameTaskVersion, putGameTaskVersion } from '@/api/gameTask'
import { getAllProducts } from '@/api/product'
import { getAllImages, getImageDetail } from '@/api/image'
import { getGameDeployDetail } from '@/api/gameDeploy'
import { getAllScenarios } from '@/api/scenario'
import { getAllModels } from '@/api/model'
import { getAllModelVersions } from '@/api/modelversion'
export default {
  data() {
    return {
      active: 1,
      addForm: { status: 0, type: 2 }, // type: 1-模型训练, 2模型部署
      port_list: [{ protocol: '2' }],
      parameter_list: [{}],
      mainNode: { visibility: '2', engine: '2', imageOptions: [], type: 1, pod_num: 1 },
      slaveNodeList: [],
      simulation_deduction_list: [],
      simulation_port_list: [{ protocol: 2 }],
      submitRules: {},
      simulation: { pod_num: 1 },
      imageOptions: [],
      productOptions: [],
      game_task_id: this.$route.query.game_task_id,
      version: this.$route.query.version,
      versionID: this.$route.query.id, //复制id
      scenarioOptions: [],
      simulationImageOptions: [],
      modelOptions: [],
      modelVersionOptions: [],
      scenario: null,  
      bizId: this.$route.query.game_task_id    
    };
  },
  components: {
  },
  async created() {
    this.getData()
    this.getSimulationImage()
    this.getModelList()
  },
  methods: {
    async setAddForm() {
      this.addForm.node_group_list = []
      this.addForm.simulation_port_list = this.simulation_port_list
      this.addForm.simulation_deduction_list = this.simulation_deduction_list
      this.addForm.simulation_node_group = this.simulation
      this.addForm.simulation_node_group.image_id = this.simulation.image.id
      this.addForm.scenario_id = this.scenario.id
      console.log('simulation_deduction_list', this.simulation_deduction_list)
      this.addForm.node_group_list = []
      this.mainNode.type = 1
      this.addForm.node_group_list.push(this.mainNode)
      for (let i = 0; i < this.slaveNodeList.length; i++) {
        this.slaveNodeList[i].type = 2
        this.addForm.node_group_list.push(this.slaveNodeList[i])
      }
      this.addForm.parameter_list = []
      for (let i = 0; i < this.parameter_list.length; i++) {
        if (this.parameter_list[i].name != null && this.parameter_list[i].length > 0) {
          if (this.parameter_list[i].name == null || this.parameter_list[i].value == null) {
            alert('参数不能为空')
          }
          else {
            this.addForm.parameter_list.push(this.parameter_list[i])
          }
        }
      }    
    },
    async getAddForm(data) {
      console.log('data', data)
      this.addForm = data
      // 仿真环境
      this.simulation = data.simulation_node_group
      await this.getSimulationImage()
      let imageRes = await getImageDetail({id: this.simulation.image_id})
      this.simulation.image = imageRes.data      
      // 仿真环境端口
      this.simulation_port_list = this.simulation.image.port_list
      // 想定
      let scenarioRes = await getAllScenarios({ image_id: this.simulation.image_id })
      this.scenarioOptions = scenarioRes.data      
      this.scenario = data.scenario
      // 仿真推演方
      this.simulation_deduction_list = data.simulation_deduction_list
      if (this.simulation_deduction_list) {
        for (let index in this.simulation_deduction_list) {
          // 推演方类型
          this.simulation_deduction_list[index].type = this.simulation_deduction_list[index].model_version_id ? 1 : 0
          // 推演算法模型版本
          if (this.simulation_deduction_list[index].model_id) {            
            await this.getModelVersionList(this.simulation_deduction_list[index].model_id, index)            
          }
        }
      }
      // 分离节点
      this.slaveNodeList = []
      console.log('nodeGroup', data.node_group_list)
      for (let node of data.node_group_list) {
        if (node.type == 1) {
          this.mainNode = node;
          let mainImage = this.mainNode.image;
          this.mainNode.visibility = mainImage.visibility
          this.mainNode.engine = mainImage.engine
          this.mainNode.image_id = mainImage.id
          this.changeMasterEngine(mainImage.visibility, mainImage.engine);
        } else {          
          let slaveImage = node.image;
          node.visibility = slaveImage.visibility
          node.engine = slaveImage.engine
          node.image_id = slaveImage.id
          this.slaveNodeList.push(node);   
          this.changeSlaveEngine(slaveImage.visibility, slaveImage.engine, this.slaveNodeList.length - 1);
        }
      }
      
      // 超参列表
      this.parameter_list = [{}]
      if (data.parameter_list.length) {
        this.parameter_list = data.parameter_list
      }
    },
    ExperimentToTask(data) {
      data.id = null
      if (data.node_group_list) {
        for (let node of data.node_group_list) {
          node.id = null
        }
      }

      console.log('ExperimentToTask', data)
    },
    async getData() {
      console.log('query', this.$route.query)
      if (this.$route.query.id) {
        this.active = 9
        let res = await getGameDeployDetail({ id: this.$route.query.id })
        let data = res.data
        console.log('res', res.data)
        this.getAddForm(data)
      } 
      else {
        this.addForm.game_task_id = this.game_task_id
        this.addForm.version = 'v' + this.version
        this.changeMasterEngine(this.mainNode.visibility, this.mainNode.engine)
      }
      this.getProductList()

    },
    infoDataset(datasets) {
      this.addForm.datasetList = datasets
    },

    async getProductList() {
      let res = await getAllProducts()
      this.productOptions = res.data
    },
    async getSimulationImage() {
      let ret = await getAllImages({ visibility: '1', type: 3 })
      this.simulationImageOptions = ret.data
    },

    async changeSimulationImage(image) {
      console.log('image', image)
      let ret = await getAllScenarios({ image_id: image.id })
      this.scenarioOptions = ret.data
      this.simulation_port_list = image.port_list
      this.simulation.command = image.command
    },
    async changeScenario(scenario) {
      this.simulation_deduction_list = []
      for (let deduction of scenario.deduction_list) {
        let data = {
          name: deduction.name,
          deduction_id: deduction.id,
        }
        this.simulation_deduction_list.push(data)
      }
      console.log('simulation_deduction_list', this.simulation_deduction_list)
    },
    async changeModel(model_id, index) {
      this.getModelVersionList(model_id, index)
    },
    async getModelList() {
      let res = await getAllModels({ visibility: '0' })
      this.modelOptions = res.data
    },
    async getModelVersionList(modelID, index) {
      console.log('index', index)
      let res = await getAllModelVersions({ model_id: modelID })
      console.log(' this.simulation_deduction_list[index]', this.simulation_deduction_list)
      this.simulation_deduction_list[index].modelVersionOptions = res.data
      this.simulation_deduction_list[index].model_version_id = null
      this.$forceUpdate()
    },
    changeModelVersion() {
      this.$forceUpdate()
    },    
    onInput() {
      this.$forceUpdate();
    },
    addParam() {
      this.parameter_list.push({})
    },
    delParam(i) {
      this.parameter_list.splice(i, 1)
    },

    async changeMasterEngine(visibility, engine) {
      console.log('ret', visibility, engine)
      let ret = await getAllImages({ visibility: visibility, engine: engine, type: 1 })
      this.mainNode.imageOptions = ret.data
    },
    async changeSlaveEngine(visibility, engine, i) {
      let res = await getAllImages({ visibility: visibility, engine: engine, type: 1 })
      this.slaveNodeList[i].imageOptions = res.data
    },
    addSlaveNode() {
      this.slaveNodeList.push({ visibility: '2', engine: '2', imageOptions: [], pod_num: 1 })
    },
    delSlaveNode(i) {
      this.slaveNodeList.splice(i, 1)
    },
    async submmit() {
      this.setAddForm()
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          let ret = await putGameTaskVersion({ ...this.addForm })
          if (ret && ret.data) {
            this.active = 3
          }
        }
      })
    },
    async updateSubmmit() {
      this.setAddForm()
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          let ret = await putGameTaskVersion({ ...this.addForm })
          if (ret && ret.data) {
            this.active = 3            
            this.toDetail()
          }
        }
      })
    },
    startTask() {

    },
    toDetail() {
      console.log('addForm', this.addForm)
      let query = {
        id: this.addForm.id
      }
      this.$router.push({
        path: '/gameDeploy/code',
        query
      })
    },
    addTaskVersion() {
      this.setAddForm()
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (this.$route.query.id) {
            this.active = 3;
          } else {
            let res = await addGameTaskVersion(this.addForm);
            this.addForm = res.data
            this.bizId = res.data.id
            if (res && res.data) {
              this.active = 3;
            }
          }
        }
      })
    }
  },

}
</script>
<style lang="less" scoped>
@import "~@/assets/css/detail-add.less";
</style>